package com.anycl.springboot.springbootinaction.advice;

import com.anycl.springboot.springbootinaction.exception.FileNotUploadException;
import com.anycl.springboot.springbootinaction.util.UnifyResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    @ExceptionHandler(FileNotUploadException.class)
    public UnifyResponse handleFileNotUploadException(Exception e, HttpServletRequest request) {
        log.info(request.getRequestURI() + "——" + e.getMessage());
        String method = request.getMethod();
        UnifyResponse response =
                new UnifyResponse(1001, "服务器内部错误", "url: " + request.getRequestURI() + " method: " + method);
        return response;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model model) {
        log.info(e.getMessage());
        model.addAttribute("error", e.getMessage());
        return "error";
    }
}
